import json

from fastapi import HTTPException
from starlette import status

from api.v1.models import UserInDB
from utils.authorization import create_token
from utils.password import verify_password


async def user_check(username: str, password: str) -> dict:
    """
    用户校验
    :param username:
    :param password:
    :return:
    """
    roles = []
    permissions = []

    user: UserInDB = await UserInDB.get(username=username).prefetch_related("roles__permissions")

    if user is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )

    if not verify_password(password, user.password):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="密码错误"
        )

    for role in user.roles:
        roles.append(role.name)
        for permission in role.permissions:
            permissions.append(permission.__dict__)

    access_token = create_token(
        data={
            "user_id": user.id,
            "roles": json.dumps(roles),
            "is_admin": user.is_admin,
            "is_frozen": user.is_frozen,
            "permissions": json.dumps(permissions)
        }
    )

    user.role = roles
    user.permissions = permissions
    data = {"userInfo": user, "access_token": access_token, "token_type": "bearer"}

    return data